package com.cj.mobile.iabp.app.dialog;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.PopupWindow;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cj.mobile.iabp.R;
import com.cj.mobile.iabp.mvp.ui.adapter.DropDownBoxAdapter;
import com.jess.arms.utils.ArmsUtils;

import java.util.List;

/**
 * 描述：下拉框弹窗
 */
public class PopupDropDownBoxWindow {
    private PopupWindow popupWindow;
    private RecyclerView recyclerView;
    private DropDownBoxAdapter adapter;
    private Context context;
    private View parent;
    private EditText editText;
    private int popupHeight;

    /**
     * 构造函数
     *
     * @param context  句柄
     * @param parent   EditText的父控件
     * @param editText 输入框
     * @param data     下拉数据源
     */
    public PopupDropDownBoxWindow(Context context, View parent, EditText editText, List<String> data) {
        this.context = context;
        this.parent = parent;
        this.editText = editText;
        this.popupHeight = ArmsUtils.dip2px(context, 200);
        initPopupWindow(data);
    }

    private void initPopupWindow(List<String> data) {
        // 创建PopupWindow的内容视图
        LayoutInflater inflater = LayoutInflater.from(context);
        View popupView = inflater.inflate(R.layout.popup_dropdownbox_list, null);

        recyclerView = popupView.findViewById(R.id.popupRecyclerView);

        // 设置适配器
        adapter = new DropDownBoxAdapter(data, installer -> {
            // 选中项的处理
            editText.setText(installer);
            editText.setSelection(installer.length());
            adapter.setSelectedItem(installer);
            dismiss();

            // 隐藏键盘
            hideKeyboard();
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapter);

        // 创建PopupWindow
        popupWindow = new PopupWindow(
                popupView,
                parent.getWidth(), // 宽度与EditText一致
                popupHeight,
                false  // 关键：不获取焦点，允许EditText继续输入
        );

        // 重要配置
        popupWindow.setFocusable(false);      // 不获取焦点，EditText可继续输入
        popupWindow.setTouchable(true);       // 允许触摸
        popupWindow.setOutsideTouchable(true); // 点击外部可关闭
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        // 关键修改：设置输入模式，让软键盘可以盖住PopupWindow
//        popupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
//        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        // 设置动画
//        popupWindow.setAnimationStyle(R.style.PopupAnimation);

        // 点击外部关闭
        popupWindow.setTouchInterceptor((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                dismiss();
                return true;
            }
            return false;
        });
    }

    /**
     * 显示PopupWindow
     */
    public void show() {
        if (!popupWindow.isShowing()) {
            editText.post(() -> {
                // 确保parent已经完成布局
                if (parent.getWidth() == 0) {
                    // 如果宽度为0，重新测量
                    parent.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                }

                // 更新PopupWindow宽度为parent的宽度
                popupWindow.setWidth(parent.getWidth());

                // 获取屏幕高度
                int screenHeight = context.getResources().getDisplayMetrics().heightPixels;

                // 计算PopupWindow的位置（显示在EditText正下方，左右对齐）
                int[] location = new int[2];
                parent.getLocationOnScreen(location);
                int editTextBottom = location[1] + parent.getHeight();

                // 计算可用空间
                int availableSpaceBelow = screenHeight - editTextBottom;
                int availableSpaceAbove = location[1];

                // 估算软键盘高度（通常为256dp左右）
                int estimatedKeyboardHeight = ArmsUtils.dip2px(context, 256);

                // 判断显示位置
                if (availableSpaceBelow >= popupHeight + estimatedKeyboardHeight) {
                    // 下方空间充足，显示在下方
                    showBelowEditText(location, editTextBottom);
                } else if (availableSpaceAbove >= popupHeight) {
                    // 上方空间充足，显示在上方
                    showAboveEditText(location);
                } else {
                    // 上下空间都不足，动态调整高度显示在下方
                    showWithAdjustedHeight(location, editTextBottom, availableSpaceBelow);
                }
            });
        }
    }

    /**
     * 在EditText下方显示
     */
    private void showBelowEditText(int[] location, int editTextBottom) {
        popupWindow.showAtLocation(
                parent,
                Gravity.NO_GRAVITY,
                location[0],
                editTextBottom
        );
    }

    /**
     * 在EditText上方显示
     */
    private void showAboveEditText(int[] location) {
        popupWindow.showAtLocation(
                parent,
                Gravity.NO_GRAVITY,
                location[0],
                location[1] - popupHeight
        );
    }

    /**
     * 动态调整高度显示
     */
    private void showWithAdjustedHeight(int[] location, int editTextBottom, int availableSpaceBelow) {
        // 保留一些边距，避免紧贴键盘
        int margin = ArmsUtils.dip2px(context, 8);
        int adjustedHeight = availableSpaceBelow - margin;

        if (adjustedHeight > ArmsUtils.dip2px(context, 100)) { // 最小高度限制
            popupWindow.setHeight(adjustedHeight);
            popupWindow.showAtLocation(
                    parent,
                    Gravity.NO_GRAVITY,
                    location[0],
                    editTextBottom
            );
        } else {
            // 如果调整后高度仍然太小，显示在上方
            showAboveEditText(location);
        }
    }

    /**
     * 监听软键盘状态并调整PopupWindow位置
     */
    public void setupKeyboardListener() {
        final View rootView = editText.getRootView();
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect r = new Rect();
            rootView.getWindowVisibleDisplayFrame(r);

            int screenHeight = rootView.getHeight();
            int keyboardHeight = screenHeight - r.bottom;

            // 如果键盘高度超过一定阈值，认为键盘已显示
            if (keyboardHeight > screenHeight * 0.15) {
                // 键盘显示时，重新计算PopupWindow位置
                if (popupWindow != null && popupWindow.isShowing()) {
                    // 延迟执行，等待布局稳定
                    editText.postDelayed(this::repositionPopupWindow, 50);
                }
            }
        });
    }

    /**
     * 重新定位PopupWindow
     */
    private void repositionPopupWindow() {
        if (popupWindow != null && popupWindow.isShowing()) {
            // 先关闭再重新显示，使用新的位置计算
            popupWindow.dismiss();
            editText.postDelayed(this::show, 100);
        }
    }

    /**
     * 显示PopupWindow（备用方法，使用showAsDropDown）
     */
    public void showAsDropDown() {
        if (!popupWindow.isShowing()) {
            editText.post(() -> {
                // 更新PopupWindow宽度为EditText的宽度
                popupWindow.setWidth(parent.getWidth());

                // 使用showAsDropDown，会自动对齐到EditText下方
                popupWindow.showAsDropDown(parent, 0, 0);
            });
        }
    }

    /**
     * 隐藏PopupWindow
     */
    public void dismiss() {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    /**
     * 设置PopupWindow高度
     */
    public void setPopupHeight(int heightDp) {
        this.popupHeight = ArmsUtils.dip2px(context, heightDp);
        if (popupWindow != null) {
            popupWindow.setHeight(this.popupHeight);
        }
    }

    /**
     * 筛选数据
     */
    public void filterData(String query) {
        if (adapter != null) {
            adapter.setSelectedItem(query);
            adapter.filter(query);
        }
    }

    /**
     * 显示所有数据
     */
    public void showAllData() {
        if (adapter != null) {
            adapter.showAllData();
        }
    }

    /**
     * 更新数据
     */
    public void updateData(List<String> newData) {
        if (adapter != null) {
            adapter.updateData(newData);
        }
    }

    /**
     * 检查是否正在显示
     */
    public boolean isShowing() {
        return popupWindow != null && popupWindow.isShowing();
    }

    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }
}
